'use strict'

const Controller = require('egg').Controller
const EquipmentModel = require('../../models/equipment')

const UserBoundDeviceModel = require('../../models/user_bound_device')

// inset ： 设备名称、设备ID
// 查询 ： 关联用户表
// update : 删除设备

class EquipmentController extends Controller {
  equipmentModel = EquipmentModel(this.app.model)
  userBoundDeviceModel = UserBoundDeviceModel(this.app.model)
  async create() {
    const { ctx, app } = this
    const { name, equipmentId: equipment_id } = ctx.query
    if (!name || !equipment_id) {
      return ctx.failure('参数非法')
    }

    //根据equipmentId查询是否已经存在
    const equipment = await this.equipmentModel.findAll({
      where: {
        equipment_id,
        del_flag: 0,
      },
    })
    if (equipment.length > 0) {
      console.log('设备以存在: ', equipment_id)
      return ctx.failure('设备以存在')
    }

    const transaction = await app.model.transaction() // 启用事务
    try {
      const equipmentModelId = ctx.helper.generateId()
      const result = await this.equipmentModel.create(
        {
          name,
          equipment_id,
          id: equipmentModelId,
          type: 2,
          del_flag: 0,
        },
        { transaction }
      )
      await this.userBoundDeviceModel.create(
        {
          id: ctx.helper.generateId(),
          user_id: ctx.userId,
          equipment_id: equipmentModelId,
          del_flag: 0,
        },
        { transaction }
      )
      await transaction.commit()
      return ctx.success('插入成功', result)
    } catch (error) {
      await transaction.rollback() // 回滚事务
      return ctx.failure('系统异常', error)
    }
  }

  async query() {
    const { ctx } = this
    const where = { del_flag: '0' }
    try {
      const result = await this.equipmentModel.findAll({ where })
      ctx.success('成功', result)
    } catch (error) {
      return ctx.failure('系统异常', error)
    }
  }

  async update() {
    const { ctx } = this
    const { equipmentId: equipment_id, name } = ctx.query
    if (!equipment_id || !name) {
      return ctx.success('请传入正确的equipmentId和设备名称')
    }
    const where = {
      equipment_id,
    }
    try {
      const result = await this.equipmentModel.update({ name }, { where })
      ctx.success('更新成功', result)
    } catch (error) {
      ctx.failure('系统异常', error)
    }
  }

  async delete() {
    const { ctx } = this
    const { equipmentId: equipment_id } = ctx.query
    const where = {
      id: equipment_id,
    }
    try {
      const result = await this.equipmentModel.destroy({ where })
      await this.userBoundDeviceModel.destroy({
        where: {
          equipment_id,
          user_id: ctx.userId
        },
      })
      ctx.success('更新成功', result)
    } catch (error) {
      ctx.failure('系统异常', error)
    }
  }
}

module.exports = EquipmentController
